function typeFormatter(value, row, index) {
    if (value == undefined || value == "") return "";
    else if (value == 1)
        return "全部商品";
    else if (value == 1)
        return "店家推荐";
    else if (value == 2)
        return "拼团商品";
    else if (value == 3)
        return "砍价商品";
    else if (value == 4)
        return "限时购商品";
    else if (value == 5)
        return "爆款商品";
    else if (value == 6)
        return "抽奖商品";
    else if (value == 7)
        return "预约服务";
    else if (value == 8)
        return "实物商品";
    else return ""
}

function sjFormatter(value, row, index) {
    if (value == undefined || value == "") return "已下架";
    else if (value == 1)
        return "已上架";
    else return "已下架";
}

function nomFormatter(value, row, index) {
    var state = row.state;
    var id = row.id;
    var res = '';

    res += ' <button typ-e="button" class="btn-sm btn-info" onclick="move(\'' + row.id + '\',\'' + row.sort + '\',' + index + ',true)">上移</button>';
    res += ' <button typ-e="button" class="btn-sm btn-info" onclick="move(\'' + row.id + '\',\'' + row.sort + '\',' + index + ',false)"">下移</button>';
    res += ' <button data-toggle="modal" class="btn-sm btn-primary" href="list.html#modal-form" data-row=' + id + ' data-index=' + index + '>修改</button>';
    if (state == undefined) {
    } else if (state == 1)
        res += ' <button type="button" class="btn-sm btn-info" onclick="changeState(\'' + id + '\',-1)" >禁用</button>';
    else
        res += ' <button typ-e="button" class="btn-sm btn-info" onclick="changeState(\'' + id + '\',1)" >启用</button>';
    res += ' <button typ-e="button" class="btn-sm btn-danger" onclick="deleteOne(\'' + id + '\')">删除</button>';
    return res;
}

function move(id, sort, index, isUp) {
    //查找上一行的序号
    console.log('--------id=' + id)
    console.log('--------sort=' + sort)
    console.log('--------index=' + index)
    console.log('--------isUp=' + isUp)
    var toIx = isUp ? index - 1 : index + 1, row = $('#mytable').bootstrapTable("getData")[toIx], moveId = row.id,moveSort = row.sort
    console.log('--------row=')
    console.log(row)
    if ((isUp && index > 0) || (!isUp && index < 19)) {
        $.ajax({
            type: 'POST',
            url: "moveSore",
            data: {
                currendId: id,
                currentSort: sort,
                moveId: moveId,
                moveSort: moveSort
            },
            success: function () {
                swal({title: "操作成功", text: "", type: "success"})
                $('#mytable').bootstrapTable('refresh');
            },
            dataType: "json"
        });
    }
}

function categoryChange(value) {
    console.log("==========shanpinChange value=" + value)
    $("#hidcid").val(value)
    console.log("==========shanpinChange value=" + $("#hidcid").val())

    var txt = $('#categorysel').find("option[value='" + value + "']").text()
    console.log("=======text" + txt)
    $("#name2").val(txt)
}

$("#mfilepic").fileinput({
    showPreview: true,
    showUpload: true,
    maxFilesNum: 1,
    uploadLabel: "上传", removeLabel: "移除", language: "zh",
    elErrorContainer: '#kartik-file-errors',
    uploadUrl: '/admin/upload/file?type=DisplayFenlei&f=pic',
    allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
}).on("fileuploaded", function (event, data) {
    console.log(data);
    $("#hidpic").val(data.response.data);
})

function changeState(id, state) {
    $.ajax({
        type: 'POST',
        url: "changeState",
        data: {
            id: id,
            state: state
        },
        success: function () {
            $('#mytable').bootstrapTable('refresh', {url: '/admin/displayfenlei/list'});
        },
        dataType: "json"
    });
}

function deleteOne(id) {
    swal({
        title: '您确定要删除此行数据？',
        text: '你将无法恢复它！',
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#ed5666',
        confirmButtonText: '确定删除！',
        cancelButtonText: '取消删除！',
        confirmButtonClass: 'btn btn-success',
        cancelButtonClass: 'btn btn-danger',
        buttonsStyling: false
    }).then(function () {

        $.ajax({
            type: 'POST',
            url: "deleteOne",
            data: {
                id: id,
            },
            success: function (status) {
                if (status == 1) {
                    swal({title: "删除成功", text: "", type: "success"})
                    $('#mytable').bootstrapTable('refresh', {url: '/admin/displayfenlei/list'});
                } else {
                    swal({title: "删除失败", text: "", type: "error"})
                }
            },
            dataType: "json"
        });

    }, function (dismiss) {
        // dismiss的值可以是'cancel', 'overlay',
        // 'close', 'timer'
        if (dismiss === 'cancel') {
            swal({title: '您已取消操作！', text: '', timer: 2000})
        }
    })
}

function displayFL(gid, gdcid) {
    console.log("===========gid=" + gid)
    console.log("===========gdcid=" + gdcid)
    $("#hidgid").val(gid)
    $('#gdcid').find("option[value='" + gdcid + "']").attr("selected", true);

    $('#displayFL-form').modal("show");

    var gdcid = $("#gdcid").val()
    $.ajax({
        type: 'POST',
        url: "modify",
        data: {
            id: gid,
            gdcid: gdcid
        },
        success: function () {
            swal({title: "操作成功", text: "", type: "success"})
            $('#mytable').bootstrapTable('refresh');
        },
        dataType: "json"
    });
}

function savedisplayFL() {
    console.log("===================savedisplayFL")
    var gid = $("#hidgid").val()
    var gdcid = $("#gdcid").val()
    console.log("===================savedisplayFL gid=" + gid)
    console.log("===================savedisplayFL gdcid=" + gdcid)
    $.ajax({
        type: 'POST',
        url: "/admin/goods/update",
        data: {
            id: gid,
            gdcid: gdcid
        },
        success: function (r) {
            console.log("=================savedisplayFL post ok")
            swal({title: "操作成功", text: "", type: "success"})
            $('#mytable').bootstrapTable('refresh');
            $('#displayFL-form').modal("hide");
            console.log("=================savedisplayFL post ok  444")
        },
        dataType: "json"
    });
}

function cancleisplayFL(gid) {
    console.log("===================cancleisplayFL gid=" + gid)
    $.ajax({
        type: 'POST',
        url: "/admin/goods/update",
        data: {id: gid, gdcid: 0},
        success: function (r) {
            console.log("=================cancleisplayFL post ok")
            swal({title: "操作成功", text: "", type: "success"})
            $('#mytable').bootstrapTable('refresh');
        },
        dataType: "json"
    });
}

function sjactFormatter(value, row, index) {
    var state = row.state;
    var id = row.id;
    var gdcid = row.gdcid;
    var isNav = row.isNav;
    var type = row.type;
    var id = row.id;
    var pic = row.pic;
    var res = '<button type="button" class="btn-sm btn-info" onclick="displayFL(\'' + id + '\',\'' + gdcid + '\')" >设置首页分类</button>';
    res += ' <button type="button" class="btn-sm btn-info" onclick="cancleisplayFL(\'' + id + '\')" >取消首页显示</button>';
    return res;
}

var editsw = [];

/**
 * 为模态框填充数据
 */
$('#modal-form').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget); // 触发事件的按钮
    var index = button.data('index');
    var modal = $(this);
    var data = $('#mytable').bootstrapTable("getData")[index]
    console.log(data)

    modal.find('#id').val(data.id)
    modal.find('#name').val(data.name)
    modal.find('#showname').val(data.showname)

    modal.find('#mpath').val(data.mpath)
    modal.find('#mval').val(data.mval)
    modal.find('#mkey').val(data.mkey)

    modal.find('#mtype').find("option[value='" + data['mtype'] + "']").attr("selected", true);
    modal.find('#show').find("option[value='" + data['show'] + "']").attr("selected", true);
    modal.find('#headType').find("option[value='" + data['headType'] + "']").attr("selected", true);
    modal.find('#type').find("option[value='" + data['type'] + "']").attr("selected", true);
    modal.find('#listtype').find("option[value='" + data['listtype'] + "']").attr("selected", true);
    $("#hidpic2").val(data.pic)
    modal.find('#sort').val(data.sort)

    // 此部分需要注意：如果页面有两个以上的图片编辑
    $("#mfilepic2").fileinput('destroy');
    $("#mfilepic2").fileinput({
        showPreview: true,
        showUpload: true,
        append: false,
        maxFilesNum: 1,
        uploadClass: "btn btn-info",
        uploadLabel: "上传", removeLabel: "移除", language: "zh",
        uploadIcon: "<i class=\"glyphicon glyphicon-upload\"></i> ",
        initialPreviewShowDelete: true,
        initialPreviewAsData: true,
        initialPreviewFileType: 'image',
        initialPreview: getPreviewList(data.pic),
        previewFileIcon: '<i class="fa fa-file"></i>',
        allowedPreviewTypes: ['image'],
        initialPreviewConfig: getPreviewConfig(data.pic, 'DisplayFenlei', "pic", data.id),
        elErrorContainer: '#kartik-file-errors',
        uploadUrl: '/admin/upload/file?type=DisplayFenlei&f=pic',
        allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
    }).on("fileuploaded", function (event, data) {
        console.log(data);
        $("#hidpic2").val(data.response.data);
    }).on('filedeleted', function (event, key, jqXHR, data) {
        console.log('Key = ' + key);
        $("#hidpic2").val('');
    })
})

//tableHeight函数
function tableHeight() {
    //可以根据自己页面情况进行调整
    return $(window).height() - 200;
}

//请求服务数据时所传参数
function initSubTable(index, row, $detail) {
    console.log(index)
    console.log(row)
    console.log($detail)
    var gdcid = row.id;
    console.log("===================row=" + row)
    console.log("===================gdcid=" + gdcid)
    var cur_table = $detail.html('<table></table>').find('table');
    $(cur_table).bootstrapTable({
        url: "/admin/goods/displaylist",
        method: 'get',
        queryParams: {gdcid: gdcid, offset: 0, limit: 20},
        clickToSelect: true,
        detailView: false,//父子表
        uniqueId: "id",
        dataField: "records",
        queryParamsType: 'limit',
        locale: 'zh-CN',//中文支持,
        sidePagination: 'server',
        pagination: false,//是否分页
        columns: [
            {
                title: '全选',
                field: 'select',
                checkbox: true,
                width: 25,
                align: 'center',
                valign: 'middle'
            },
            {
                title: 'ID',
                field: 'id',
                visible: false
            },
            {
                title: '商品名',
                field: 'name'
            },
            // {
            //     title: '商品编号',
            //     field: 'goodsNo'
            // },
            {
                title: '商品原价',
                field: 'price'
            },
            {
                title: '实际售价',
                field: 'saleprice'
            },
            {
                title: '最低价',
                field: 'minPrice'
            },
            {
                title: '订单数',
                field: 'numberOrders'
            },
            {
                title: '销量数',
                field: 'numberSale'
            },
            {
                title: '总库存数',
                field: 'stores'
            },
            {
                title: '商品主图',
                field: 'pic',
                formatter: "imgFormatter"
            },

            {
                title: '支持会员卡',
                field: 'isMember',
                formatter: "sfFormatter"
            },
            {
                title: '支持积分',
                field: 'isJifen',
                formatter: "sfFormatter"
            },
            {
                title: '支持优惠券',
                field: 'isCoupon',
                formatter: "sfFormatter"
            },
            {
                title: '上架状态',
                field: 'state',
                formatter: "sjFormatter"
            },
            {
                title: '操作',
                field: 'Attribute',
                align: 'center',
                width: 320,
                formatter: sjactFormatter
            }]
    })
}

$(function () {

    var sw = [];
    $(".js-switch").each(function (i, e) {
        sw[i] = new Switchery(e, {color: "#1AB394"})
    })
    $(window).resize(function () {
        $('#mytable').bootstrapTable('resetView', {
            height: tableHeight()
        })
    })
    //生成用户数据
    $('#mytable').bootstrapTable({
        method: 'get',
        url: "/admin/displayfenlei/list",
        // height:520,//高度调整
        // toolbar: '#toolbar',
        striped: true, //是否显示行间隔色
        dataField: "records",
        pagination: true,//是否分页
        queryParamsType: 'limit',
        queryParams: queryParams,
        sidePagination: 'server',
        pageNumber: 1, //初始化加载第一页，默认第一页
        pageSize: 50,//单页记录数
        pageList: [50, 100, 200, 500],//分页步进值
        showExport: true,//显示导出
        showRefresh: false,//刷新按钮
        showColumns: false,
        clikToSelect: true,//是否启用点击选中行
        detailView: true,//父子表
        // toolbarAlign:'right',
        // buttonsAlign:'right',//按钮对齐方式
        onExpandRow: function (index, row, $detail) {
            initSubTable(index, row, $detail);
        },
        columns: [
            {
                title: '全选',
                field: 'select',
                checkbox: true,
                width: 25,
                align: 'center',
                valign: 'middle'
            },
            {
                title: 'ID',
                field: 'id',
                visible: false
            },
            {
                title: '分类名',
                field: 'name'
            },
            {
                title: '展示分类名',
                field: 'showname'
            },
            // {
            //     title: '展示分类类别',
            //     field: 'type',
            //     formatter: "typeFormatter"
            // },
            {
                title: '显示图',
                field: 'pic',
                formatter: "imgFormatter"
            },
            {
                title: '排序',
                field: 'sort'
            },
            {
                title: '启用状态',
                field: 'state',
                formatter: "stateFormatter"
            },
            {
                title: '操作',
                field: 'Attribute',
                align: 'center',
                width: 280,
                formatter: nomFormatter
            }
        ],
        locale: 'zh-CN',//中文支持,
    })

    //请求服务数据时所传参数
    function queryParams(params) {
        var p = {
            limit: params.limit,
            offset: params.offset,
            sort: params.sort,
            order: params.order
            , search: $('#search').val() || ""
            , status: $('#qstatus').val() || 99
        }
        return p;
    }

    $('#search_btn').click(function () {
        var p = {
            status: $('#qstatus').val(),
            search: $('#search').val(),
            ts: new Date().getTime()
        };
        $('#mytable').bootstrapTable('refresh', p);
    })

    /*
     * 验证错误提示信息高亮
     */
    $.validator.setDefaults({
        highlight: function (e) {
            $(e).closest(".form-group").removeClass("has-success").addClass("has-error")
        }, success: function (e) {
            e.closest(".form-group").removeClass("has-error").addClass("has-success")
        }, errorElement: "span", errorPlacement: function (e, r) {
            e.appendTo(r.is(":radio") || r.is(":checkbox") ? r.parent().parent().parent() : r.parent())
        }, errorClass: "help-block m-b-none", validClass: "help-block m-b-none"
    }), $("#aform").validate(), $("#mform").validate();
})

function checkAdd() {
    $('input:checkbox').each(function (index, item) {
        if ($(this).prop("checked")) {
            $(this).val(1);
            console.log($(this).attr("name") + "=" + $(this).val())
        } else {
            $(this).val(-1);
            console.log($(this).attr("name") + "=" + $(this).val())
        }
    });
    if ($("#sort2").val() == "") {
        swal({title: "排序值不能为空", text: "", type: "warning"})
        return false;
    }
    if ($("#hidpic").attr("required") == "required"
        && $("#hidpic").val() == "") {
        swal({title: "请上传图片", text: "", type: "warning"})
        return false;
    }
    return true;
}

function checkModify() {
    $('input:checkbox').each(function (index, item) {
        if ($(this).prop("checked")) {
            $(this).val(1);
            console.log($(this).attr("id") + "=" + $(this).val())
        } else {
            $(this).val(-1);
            console.log($(this).attr("id") + "=" + $(this).val())
        }
    });
    if ($("#sort").val() == "") {
        swal({title: "排序值不能为空", text: "", type: "warning"})
        return false;
    }
    if ($("#hidpic2").attr("required") == "required"
        && $("#hidpic2").val() == "") {
        swal({title: "请上传图片", text: "", type: "warning"})
        return false;
    }
    return true;
}